var barcode = require('./barcode');
var qrcode = require('./qrcode');
const htp = "http://ceshi4.sdykt.com.cn:1280/api-o2o";

function convert_length(length) {
  return Math.round(wx.getSystemInfoSync().windowWidth * length / 750);
}

function barc(id, code, width, height) {
  barcode.code128(wx.createCanvasContext(id), code, convert_length(width), convert_length(height))
}

function qrc(id, code, width, height) {
  qrcode.api.draw(code, {
    ctx: wx.createCanvasContext(id),
    width: convert_length(width),
    height: convert_length(height)
  })
}

function checkPhone(t) {
  if (!(/^1(3|4|5|7|8)\d{9}$/.test(t))) {
    return false;
  }
  return true;
}

function httServer(port, jsonParm, callback) {
  var dic = jsonParm;
  var sdic = Object.keys(dic).sort();
  var tempstr = '';
  for (var ki in sdic) {
    console.log(sdic[ki] + ":" + dic[sdic[ki]] + ",");
    tempstr += sdic[ki] + "=" + dic[sdic[ki]] + '&';
  }
  tempstr = tempstr.replace(/\s+/g, "");
  tempstr = tempstr.substring(0, tempstr.length - 1)
  wx.request({
    url: htp + port,
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded' // 默认值
    },
    data: tempstr,
    success(res) {
      var rdta = res.data;
      var rcode = res.statusCode;
      if (rcode == '200') {
        if (rdta.return_code == '0000') {
          callback('', rdta);
        } else {
          callback(rdta.msg);
        }
      } else {
        callback('请求失败,返回:' + rcode);
      }

    },
    fail(e) {
      callback('请求失败')
    }
  })
}
//带token请求
function serverToken(port, jsonParm, callback) {
  var dic = jsonParm;
  var sdic = Object.keys(dic).sort();
  var tempstr = '';
  for (var ki in sdic) {
    console.log(sdic[ki] + ":" + dic[sdic[ki]] + ",");
    tempstr += sdic[ki] + "=" + dic[sdic[ki]] + '&';
  }
  tempstr = tempstr.replace(/\s+/g, "");
  tempstr = tempstr.substring(0, tempstr.length - 1)
  console.log(tempstr);
  wx.request({
    url: htp + port,
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded', // 默认值
      'auth_token': app.globalData.token
    },
    data: tempstr,
    success(res) {
      var rdta = res.data;
      var rcode = res.statusCode;
      if (rcode == '200') {
        if (rdta.return_code == '0000') {
          callback('', rdta);
        } else {
          callback(rdta.msg);
        }
      } else {
        callback('请求失败,返回:' + rcode);
      }
    },
    fail(e) {
      callback('请求失败')
    }
  })
}
module.exports = {
  barcode: barc,
  qrcode: qrc,
  checkPhone: checkPhone,
  httServer: httServer,
  serverToken: serverToken
}